package com.elitel.frame.base.controller;

import com.elitel.frame.base.component.quartz.QuartzConfigUtil;
import com.elitel.frame.base.component.quartz.QuartzScheduler;
import com.elitel.frame.base.component.quartz.SearchServiceTask;
import com.elitel.frame.base.service.BaseQueryfieldService;
import com.elitel.frame.base.service.BaseQueryfieldcacheService;
import com.elitel.frame.core.util.ExportExcel;
import com.elitel.frame.core.util.ImportExcel;
import com.elitel.frame.main.entity.BaseQueryfield;
import com.elitel.frame.main.entity.BaseQueryfieldcache;
import com.elitel.frame.main.entity.SysPrjservice;
import com.elitel.frame.main.entity.ext.BaseQueryfieldExt;
import com.elitel.frame.main.entity.ext.BaseQueryfieldcacheExt;
import com.elitel.frame.main.entity.vo.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/system/queryfieldcache")
public class BaseQueryfieldcacheController {

    @Autowired
    BaseQueryfieldService baseQueryfieldService;
    @Autowired
    BaseQueryfieldcacheService baseQueryfieldcacheService;
    @Autowired
    private QuartzScheduler quartzScheduler;
    @Autowired
    private SearchServiceTask searchServiceTask;

    /**
     * 根据serviceid和servicetype查询缓存条件的组
     * @param serviceId
     * @param serviceType
     * @return
     */
    @RequestMapping("/queryCacheFieldGroup")
    @ResponseBody
    public Object queryCacheFieldGroup(String serviceId, String serviceType) {
        List<BaseQueryfieldcacheExt> list = baseQueryfieldcacheService.queryCacheFieldGroup(serviceId, serviceType);
        return list;
    }

    /**
     * 根据serviceid和servicetype和参数组查询缓存参数和值
     * @param serviceId
     * @param serviceType
     * @param parametergroup
     * @return
     */
    @RequestMapping("/queryCacheFieldByServiceIdGroupId")
    @ResponseBody
    public Object queryCacheFieldByServiceIdGroupId(String serviceId, String serviceType, String parametergroup) {
        List<BaseQueryfieldcacheExt> list = baseQueryfieldcacheService.queryCacheFieldByServiceIdGroupId(serviceId, serviceType, parametergroup);
        return list;
    }

    /**
     * 添加缓存字段和值
     * @param list
     * @return
     */
    @RequestMapping("/addQueryFieldCacheList")
    @ResponseBody
    public Object addQueryFieldCacheList(@RequestBody List<BaseQueryfieldcache> list) {
        JsonResult jr = new JsonResult();
        try {
            Integer size = baseQueryfieldcacheService.addQueryFieldCacheList(list);
            if(size > 0) {
                SysPrjservice service = baseQueryfieldService.getServiceByFieldGuid(list.get(0).getFieldaddonsguid());
                //添加任务调度
                searchServiceTask.startQueryDataByCacheConfigScheduler(service.getServicecode(), service.getServicetype(), list.get(0).getParametergroup());
            }
            jr.setSuccess(true);
        } catch (Exception e) {
            jr.setMsg("添加缓存条件配置异常！");
        }

        return jr;
    }

    /**
     * 按组删除缓存配置
     * @param serviceId
     * @param serviceType
     * @param parametergroup
     * @return
     */
    @RequestMapping("/deleteQueryFieldCacheList")
    @ResponseBody
    public Object deleteQueryFieldCacheList(String serviceId, String serviceType, String parametergroup) {
        JsonResult jr = new JsonResult();
        try {
            Integer size = baseQueryfieldcacheService.deleteQueryFieldCacheList(serviceId, parametergroup);
            if(size > 0) {
                //刷新任务调度
                String jobName = QuartzConfigUtil.getJobName(serviceId, serviceType, parametergroup);
                quartzScheduler.removeJob(serviceId, jobName);
            }
            jr.setSuccess(true);
        } catch (Exception e) {
            jr.setMsg("删除缓存条件配置异常！");
            jr.setSuccess(false);
        }
        return jr;
    }

    /**
     * 修改缓存条件配置
     * @param list
     * @return
     */
    @RequestMapping("/updateQueryFieldCacheList")
    @ResponseBody
    public Object updateQueryFieldCacheList(@RequestBody List<BaseQueryfieldcache> list) {
        JsonResult jr = new JsonResult();
        try {
            Integer size = baseQueryfieldcacheService.updateQueryFieldCacheList(list);
            if(size > 0) {
                BaseQueryfieldcacheExt baseQueryfield =baseQueryfieldcacheService.getQueryFieldCacheByGuid(list.get(0).getGuid());
                //刷新任务调度
                String jobName = QuartzConfigUtil.getJobName(baseQueryfield.getServiceid(), String.valueOf(baseQueryfield.getServicetype()).trim(), baseQueryfield.getParametergroup());
                quartzScheduler.refreshJobTime(baseQueryfield.getServiceid(), jobName);
            }
            jr.setSuccess(true);
        } catch (Exception e) {
            jr.setMsg("修改缓存条件配置异常！");
            jr.setSuccess(false);
        }

        return jr;
    }

    /**
     * 根据服务ID和服务类型查询服务缓存字段配置信息（暂只支持单表）
     * @param serviceId
     * @param serviceType
     * @return
     */
    @RequestMapping("/getQueryFieldCacheConfigByServiceId")
    @ResponseBody
    public Object getQueryFieldCacheConfigByServiceId(String serviceId, String serviceType) {
        List<Map<String, Object>> list = baseQueryfieldcacheService.getQueryFieldCacheConfigByServiceId(serviceId, serviceType);
        return list;
    }

    /**
     * 下载excel模板
     * @param request
     * @param response
     */
    @RequestMapping("/exportFieldCacheInfoExcel")
    public void exportOvertimeSubsidy(HttpServletRequest request, HttpServletResponse response){
        try {
            String serviceId = request.getParameter("serviceId");
            List<BaseQueryfieldExt> baseQueryfieldlist = baseQueryfieldService.getQueryFieldListByServiceId(serviceId, "1","",1);
            String[] headers = new String[baseQueryfieldlist.size()];
            for (int i = 0; i < baseQueryfieldlist.size(); i++) {
                headers[i] = baseQueryfieldlist.get(i).getParametercode();
            }
            ExportExcel.exportExcel(serviceId,"fieldCacheConfig","条件参数值缓存配置", headers, null,  response);
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传缓存条件配置信息
     * @param file
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/uploadFieldCacheInformation")
    @ResponseBody
    public Map<String, Object> uploadUserInformation(@RequestParam("file") MultipartFile file,
                                                      HttpServletRequest request, HttpServletResponse response){

        String serviceId = request.getParameter("serviceId");
        String serviceType = request.getParameter("serviceType");
        String pcode = request.getParameter("pcode");
        Map<String, Object> map = new HashMap<>();
        try {
            String lname = file.getOriginalFilename();
            List<Map<String, Object>> importExcel = (List<Map<String, Object>>)ImportExcel.doImportExcelByInputstream(file.getInputStream(), lname, 2, 0, false, null);
            map = baseQueryfieldcacheService.updateImportFieldCacheInfo(pcode, serviceId, serviceType, importExcel);
            if ((boolean)map.get("result")) {
                Set<String> groupset = (Set<String>)map.get("quartz");
                for (String group : groupset) {
                    //刷新任务调度
                    searchServiceTask.startQueryDataByCacheConfigScheduler(serviceId, serviceType, group);
                }
            }
        } catch (Exception e) {
            map.put("result", false);
            map.put("message", "缓存配置信息上传异常！");
            e.printStackTrace();
        }
        return map;

    }
}
